package com.xiaoshuidi.cloud.module.contract.convert.contract;

import com.xiaoshuidi.cloud.module.contract.dal.dataobject.contract.TemplateDynamicTablesDO;
import com.xiaoshuidi.cloud.module.contract.service.contract.dto.ContractDynamicTablesFillDTO;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同模板动态表格 Convert
 *
 * @author 合房租赁
 */
@Mapper
public interface TemplateDynamicTablesConvert {

    TemplateDynamicTablesConvert INSTANCE = Mappers.getMapper(TemplateDynamicTablesConvert.class);

    @Mappings({
            @Mapping(source = "headers", target = "headers", qualifiedByName = "stringToStrList"),
            @Mapping(source = "colWidthPercent", target = "colWidthPercent", qualifiedByName = "stringToIntList"),
            @Mapping(source = "cellHeight", target = "cellHeight"),
            @Mapping(source = "tableWidthPercentage", target = "tableWidthPercentage"),
            @Mapping(source = "tableHorizontalOffset", target = "tableHorizontalOffset"),
    })
    ContractDynamicTablesFillDTO convertDO2FillDTO(TemplateDynamicTablesDO dynamicTablesDO);

    @Mappings({
            @Mapping(source = "headers", target = "headers", qualifiedByName = "stringToStrList"),
            @Mapping(source = "colWidthPercent", target = "colWidthPercent", qualifiedByName = "stringToIntList"),
            @Mapping(source = "cellHeight", target = "cellHeight"),
            @Mapping(source = "tableWidthPercentage", target = "tableWidthPercentage"),
            @Mapping(source = "tableHorizontalOffset", target = "tableHorizontalOffset"),
    })
    List<ContractDynamicTablesFillDTO> convertDOs2FillDTOs(List<TemplateDynamicTablesDO> dynamicTablesDOs);

    @Named("stringToStrList")
    static List<String> stringToStrList(String str){
        if (StringUtils.isNotBlank(str)){
            List<String> collect = Arrays.stream(str.split(",")).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Named("stringToIntList")
    static List<Integer> stringToIntList(String str){
        if (StringUtils.isNotBlank(str)){
            try {
                List<Integer> collect = Arrays.stream(str.split(",")).map(i -> Integer.valueOf(i)).collect(Collectors.toList());
                return collect;
            } catch (Exception e) {
                System.out.println("字符串转换数字异常");
                return null;
            }
        }
        return null;
    }


}
